#! /usr/bin/python
#-*- coding: utf-8 -*-  

partLable = ("<",">")
sectionLable = ("[","]")
#endlineLable = "\r\n" #windows
endlineLable = "\n"   #linux
equalLable = "=" #
noteLable = '#' # 
class config:
    def __init__(self,configfile):
        self.configfile = configfile
        f = open(configfile,"rb")
        self.strFileContent = f.read()
       # print self.strFileContent
        f.close()    
        # 得到总配置的map
    def getPlatformMap(self,strtmp,lable1 = partLable,lable2 = sectionLable):
        tmp = strtmp.split(lable1[0])
        tmp = [elem for elem in tmp if len(elem) > 1]
        tmp = [elem for elem in tmp if elem.rfind(lable1[1]) > 0]
        platdict = {}
        for elem in tmp:
            key = elem[0:elem.find(lable1[1]):]
            value = elem[elem.find(lable2[0])::]
            platdict[key] = value
        return platdict
    
    # 得到各部分的map
    def getSectionMap(self,strtmp,lable1 = sectionLable):
        tmp = strtmp.split(lable1[0])
        tmp = [elem for elem in tmp if len(elem) > 1]
        tmp = [elem for elem in tmp if elem.rfind(lable1[1]) > 0]
        sectionDict = {}
        for elem in tmp:
            key = elem[0:elem.find(lable1[1]):]
            value = elem[elem.find(endlineLable)+len(endlineLable)::]
            sectionDict[key] = value
        return sectionDict
    
    # 获取具体配置值
    def getValueMap(self,strtmp):
        tmp = strtmp.split(endlineLable)
        tmp = [elem for elem in tmp if len(elem) > 1]
        valueDict = {}
        for elem in tmp:
            if elem.find(noteLable) > 0: # 如果有注释则去掉注释
                elem = elem[0:elem.find(noteLable):]
            elem = ''.join(elem.split()) # 去掉空白字符
            key = elem[0:elem.find(equalLable):]
            value = elem[elem.find(equalLable)+len(equalLable)::]
        valueDict[key] = value
        return valueDict
    def getConfig(self):
        self.vardict = {}
    
        var1 = self.getPlatformMap(self.strFileContent)
    
        for k,v in var1.items():
            var2 = self.getSectionMap(v)
            dict3 = {}
            for k2,v2 in var2.items():
                var3 = self.getValueMap(v2)
                dict3[k2] = var3
	    self.vardict[k] = dict3
        return self.vardict

if __name__ == '__main__':
    configfile = "./config.txt"
    conf = config(configfile)
    vardict = conf.getConfig()
